<?php
/**
 * 权限管理
 *
 * @copyright  Copyright (c) 2010-2015 NcPHP Inc. (http://www.ncphp.com)
 * @license    http://www.ncphp.com
 * @link       http://www.ncphp.com
 * @since      File available since Release v1.1
 */
defined('InNcPHP') or exit('Access Invalid!');

class adminControl extends SystemControl{
	private $links = array(
		array('url'=>'act=admin&op=admin','lang'=>'limit_admin'),
		array('url'=>'act=admin&op=admin_add','lang'=>'admin_add_limit_admin'),
		array('url'=>'act=admin&op=group','lang'=>'limit_gadmin'),
		array('url'=>'act=admin&op=group_add','lang'=>'admin_add_limit_gadmin'),
	);

	public function __construct(){
		parent::__construct();
		Language::read('admin');
	}

	// 管理员 //
	// 列表
	public function adminOp(){
		$model = Model('admin');
		if (chksubmit()){
			//ID为1的会员不允许删除
			if (@in_array(1,$_POST['del_id'])){
				showMessage(L('admin_index_not_allow_del'));
			}
			if (!empty($_POST['del_id'])){
				if (is_array($_POST['del_id'])){
					foreach ($_POST['del_id'] as $k => $v){
						$model->delAdmin(array('admin_id'=>intval($v)));
					}
				}
				$this->log(L('nc_delete,limit_admin'),1);
				showMessage(L('nc_common_del_succ'));
			}else {
				showMessage(L('nc_common_del_succ'));
			}
		}
		$admin_info = $this->getAdminInfo();
		//查询条件
		$condition = array();
		if (isset($_GET['search_name']) && $_GET['search_name']) {
			$condition['admin.username'] = $_GET['search_name'];
		}
		if(intval($this->admin_info['merchant_id'])>0){
			$condition['admin.merchant_id'] = $this->admin_info['merchant_id'];
		}else{
			if (isset($_GET['search_merchant']) && is_numeric($_GET['search_merchant'])) {
				$condition['admin.merchant_id'] = intval($_GET['search_merchant']);
			}
		}
		if(isset($_GET['search_group']) && is_numeric($_GET['search_group'])){
			$condition['admin.group_id'] = intval($_GET['search_group']);
		}

		$admin_list = $model->getAdminJoinGroupList($condition, '*', 20, 'admin_id asc');
		if($admin_list && is_array($admin_list)){
			$merchant_model = Model('member_merchant');
			foreach($admin_list as $key => $value){
				//获取属于商家组的商家名称
				if($value['merchant_id']>0){
					$arr = $merchant_model->getMerchantInfo(array('merchant_id'=>$value['merchant_id']),'mc_shop_name');
					$admin_list[$key]['mc_shop_name'] = $arr['mc_shop_name'];
				}
			}
		}
		Tpl::output('admin_list',$admin_list);
		Tpl::output('page',$model->showpage());
		/* @var member_merchantModel $merchant_model */
		//获取商家
		$merchant_model = Model('member_merchant');
		$admin_group_model = Model('admin_group');
		if(intval($this->admin_info['merchant_id'])>0){
			$merchants = $merchant_model->getMerchantList(array('mc_status'=>1,'merchant_id'=>$this->admin_info['merchant_id']), 'merchant_id,mc_shop_name');
			//获取权限组
			$group_list = $admin_group_model->getAdminGroupList(array('g_merchant_id'=>$admin_info['merchant_id']),'group_name,group_id',1000);
		}else{
			$merchants = $merchant_model->getMerchantList(array('mc_status'=>1), 'merchant_id,mc_shop_name');
			$group_list = $admin_group_model->getAdminGroupList(array('is_merchant'=>0),'group_name,group_id',1000);
		}

		Tpl::output('search', $_GET);
        Tpl::output('group_list',$group_list);
		Tpl::output('merchants',$merchants);
		Tpl::output('top_link',$this->sublink($this->links, 'admin'));
		Tpl::showpage('admin.index');
	}

	// 添加
	public function admin_addOp(){
		$admin_info = $this->getAdminInfo();
		if(chksubmit()){
			$limit_str = '';

			$model_admin = Model('admin');
			$param['username'] = $_POST['username'];
			$param['group_id'] = $_POST['group_id'];
			$param['password'] = md5($_POST['password']);
			$param['merchant_id'] = $admin_info['merchant_id']>0?$admin_info['merchant_id']:$_POST['merchants_id'];
			$rs = $model_admin->addAdmin($param);
			if ($rs){
				$this->log(L('nc_add,limit_admin').'['.$_POST['username'].']',1);
				showMessage(L('nc_common_save_succ'),'index.php?act=admin&op=admin');
			}else {
				showMessage(L('nc_common_save_fail'));
			}
		}

		$model_admin_group = Model('admin_group');
		if($admin_info['id']==1){
			//属于超级管理员
			$gadmin = $model_admin_group->getAdminGroupList(array('g_merchant_id'=>0), 'group_id, group_name', 1000);
		}else{
			//获取除超级权限组之外的所有权限组
			if($admin_info['merchant_id']>0){
				$gadmin = $model_admin_group->getAdminGroupList(array('is_super_group'=>0,'g_merchant_id'=>$admin_info['merchant_id']), 'group_id, group_name', 1000);
			}else{
				$gadmin = $model_admin_group->getAdminGroupList(array('is_super_group'=>0,'g_merchant_id'=>0), 'group_id, group_name', 1000);
			}

		}
		//获取商家列表
		$merchant_model = Model('member_merchant');
		if($admin_info['merchant_id']>0){
			$merchants = $merchant_model->getMerchantList(array('mc_status'=>1,'merchant_id'=>$admin_info['merchant_id']), 'merchant_id,mc_shop_name');
		}else{
			$merchants = $merchant_model->getMerchantList(array('mc_status'=>1), 'merchant_id,mc_shop_name');
		}
		Tpl::output('merchants',$merchants);
		Tpl::output('gadmin',$gadmin);
		Tpl::output('top_link', $this->sublink($this->links, 'admin_add'));
		Tpl::output('limit', $this->permission());
		Tpl::showpage('admin.add');
	}	

	// 编辑
	public function admin_editOp(){
		$model_admin = Model('admin');
		$admin_info = $this->getAdminInfo();
		if (chksubmit()){
			//没有更改密码
			if ($_POST['password'] != ''){
				$data['password'] = md5($_POST['password']);
			}
			$data['group_id'] = intval($_POST['group_id']);
			$data['merchant_id'] = $admin_info['merchant_id']>0?$admin_info['merchant_id']:$_POST['merchants_id'];
			//查询管理员信息
			$admin_model = Model('admin');
			$result = $admin_model->updateAdmin(array('admin_id'=>intval($_GET['admin_id'])),$data);
			if ($result){
				$this->log(L('nc_edit,limit_admin').'[ID:'.intval($_GET['admin_id']).']',1);
				showMessage(Language::get('admin_edit_success'),'index.php?act=admin&op=admin');
			}else{
				showMessage(Language::get('admin_edit_fail'),'index.php?act=admin&op=admin');
			}
		}
		$condition = array();
		$condition['admin_id']	= intval($_GET['admin_id']);
		$info = $model_admin->getAdminInfo($condition);
		if(!is_array($info) || count($info)<=0){
			showMessage(Language::get('admin_edit_admin_error'),'index.php?act=admin&op=admin');
		}
		Tpl::output('info', $info);
		Tpl::output('top_link',$this->sublink($this->links, 'admin'));
		$model_admin_group = Model('admin_group');

		if($admin_info['id']==1){
			//属于超级管理员
			$gadmin = $model_admin_group->getAdminGroupList(array('g_merchant_id'=>0), 'group_id, group_name', 1000);
		}else{
			//获取除超级权限组之外的所有权限组
			if($admin_info['merchant_id']>0){
				//如果是商家就获取商家底下的权限组
				$gadmin = $model_admin_group->getAdminGroupList(array('is_super_group'=>0,'g_merchant_id'=>$admin_info['merchant_id']), 'group_id, group_name', 1000);
			}else{
				$gadmin = $model_admin_group->getAdminGroupList(array('is_super_group'=>0,'g_merchant_id'=>0), 'group_id, group_name', 1000);
			}
		}

		//获取商家列表
		$merchant_model = Model('member_merchant');
		if($admin_info['merchant_id']>0){
			$merchants = $merchant_model->getMerchantList(array('mc_status'=>1,'merchant_id'=>$admin_info['merchant_id']), 'merchant_id,mc_shop_name');
		}else{
			$merchants = $merchant_model->getMerchantList(array('mc_status'=>1), 'merchant_id,mc_shop_name');
		}
		Tpl::output('merchants',$merchants);
		Tpl::output('gadmin', $gadmin);
		Tpl::showpage('admin.edit');
	}

	// 删除
	function admin_delOp(){
		if (!empty($_GET['admin_id'])){
			if ($_GET['admin_id'] == 1){
				showMessage(L('nc_common_save_fail'));
			}
			$model_admin = Model('admin');
			$model_admin->delAdmin(array('admin_id'=>intval($_GET['admin_id'])));	
			$this->log(L('nc_delete,limit_admin').'[ID:'.intval($_GET['admin_id']).']',1);
			showMessage(L('nc_common_del_succ'));
		}else {
			showMessage(L('nc_common_del_fail'));
		}
	}

	// AJAX
	public function ajaxOp(){
		switch ($_GET['branch']){
			//管理人员名称验证
			case 'check_username':
				$model_admin = Model('admin');
				$condition['username'] = $_GET['username'];
				$list = $model_admin->getAdminInfo($condition);
				if (!empty($list)){
					exit('false');
				}else {
					exit('true');
				}
				break;
			//权限组名称验证
			case 'check_group_name':
				$condition = array();
				if (is_numeric($_GET['group_id'])){
					$condition['group_id'] = array('neq',intval($_GET['group_id']));
				}
				$condition['group_name'] = $_GET['group_name'];
				$info = Model('admin_group')->where($condition)->find();
				if (!empty($info)){
					exit('false');
				}else {
					exit('true');
				}
				break;
		}
	}

    // 所有权限
    private function permission() {
		Language::read('common');
		$lang = Language::getLangContent();    	
		$limit = require(BASE_PATH.'/include/limit1.php');
		//var_dump($limit);exit;
		if (is_array($limit)){
			foreach ($limit as $k=>$v) {
				if (is_array($v['child'])){
					$tmp = array();
					foreach ($v['child'] as $key => $value) {
						$act = (!empty($value['act'])) ? $value['act'] : $v['act'];
						if (strpos($act,'|') == false){//act参数不带|
							$limit[$k]['child'][$key]['op'] = rtrim($act.'.'.str_replace('|','|'.$act.'.',$value['op']),'.');
						}else{//act参数带|
							$tmp_str = '';
							if (empty($value['op'])){
								$limit[$k]['child'][$key]['op'] = $act;
							}elseif (strpos($value['op'],'|') == false){//op参数不带|
								foreach (explode('|',$act) as $v1) {
									$tmp_str .= "$v1.{$value['op']}|";
								}
								$limit[$k]['child'][$key]['op'] = rtrim($tmp_str,'|');
							}elseif (strpos($value['op'],'|') != false && strpos($act,'|') != false){//op,act都带|，交差权限
								foreach (explode('|',$act) as $v1) {
									foreach (explode('|',$value['op']) as $v2) {
										$tmp_str .= "$v1.$v2|";
									}									
								}
								$limit[$k]['child'][$key]['op'] = rtrim($tmp_str,'|');
							}
						}
					}
				}
			}
			return $limit;
		}else{
			return array();
		}
    }

	// 管理员 //
    // 列表
	public function groupOp(){
		$model = Model('admin_group');
		if (chksubmit()){
			if (@in_array(1,$_POST['del_id'])){
				showMessage(L('admin_index_not_allow_del'));
			}
			if (!empty($_POST['del_id'])){
				if (is_array($_POST['del_id'])){
					foreach ($_POST['del_id'] as $k => $v){
						$model->delAdminGroup(array('group_id'=>intval($v)));
					}
				}
				$this->log(L('nc_delete,limit_gadmin').'[ID:'.implode(',',$_POST['del_id']).']',1);
				showMessage(L('nc_common_del_succ'));
			}else {
				showMessage(L('nc_common_del_fail'));
			}
		}
		$admin_info = $this->getAdminInfo();
		if($admin_info['merchant_id']>0){
			//取属于该店铺的所有权限组
			$list = $model->getAdminGroupList(array('g_merchant_id'=>$admin_info['merchant_id']),'*',10);
		}else{
			$list = $model->getAdminGroupList(array('g_merchant_id'=>0),'*',10);
		}

		Tpl::output('list',$list);
		Tpl::output('page',$model->showpage());
		Tpl::output('top_link',$this->sublink($this->links,'group'));
		Tpl::showpage('admin.group.index');
	}

	// 添加
	public function group_addOp(){
		//检查是否是超级管理添加
		$admin_info = $this->getAdminInfo();
		if (chksubmit()){
			$limit_str = '';
			$model = Model('admin_group');
			if (is_array($_POST['permission'])){
				$limit_str = implode('|',$_POST['permission']);
			}

			$data['group_limits'] = encrypt($limit_str,MD5_KEY.md5($_POST['group_name']));
			$data['group_name'] = $_POST['group_name'];
			$data['is_super_group'] = $_POST['is_super_group']==1?1:0;
			$data['is_merchant'] = $admin_info['merchant_id']>0?1:0;
			$data['g_merchant_id'] = $admin_info['merchant_id']>0?$admin_info['merchant_id']:0;
			if ($model->addAdminGroup($data)){
				$this->log(L('nc_add,limit_gadmin').'['.$_POST['group_name'].']',1);
				showMessage(L('nc_common_save_succ'),'index.php?act=admin&op=group');
			}else {
				showMessage(L('nc_common_save_fail'));
			}
		}

		if($admin_info['id']!=1){
			//不是超级管理员 获取当前管理员的权限组
			$ginfo = Model('admin_group')->getby_group_id($admin_info['gid']);
			//解析已有权限
			$hlimit = decrypt($ginfo['group_limits'],MD5_KEY.md5($ginfo['group_name']));
			$ginfo['limits'] = explode('|',$hlimit);
			Tpl::output('ginfo',$ginfo);

		}
		Tpl::output('top_link',$this->sublink($this->links, 'group_add'));
        Tpl::output('limit',$this->permission());
		Tpl::showpage('admin.group.add1');
	}

	// 编辑
	public function group_editOp(){
		$model = Model('admin_group');
		$gid = intval($_GET['group_id']);
		$admin_info = $this->getAdminInfo();
		$ginfo = $model->getby_group_id($gid);
		if($ginfo['is_super_group']==1 && $admin_info['id']!=1){
			//属于超级权限组 其他管理员无权编辑
			showMessage('该权限组属于超级管理权限组,您无权编辑');
		}
		if (empty($ginfo)){
			showMessage(L('admin_set_admin_not_exists'));
		}
		if (chksubmit()){
			$limit_str = '';
			if (is_array($_POST['permission'])){
				$limit_str = implode('|',$_POST['permission']);
			}
			$limit_str = encrypt($limit_str,MD5_KEY.md5($_POST['group_name']));
			$data['group_limits'] 	= $limit_str;
			$data['group_name']		= $_POST['group_name'];
			$data['is_super_group'] = $_POST['is_super_group']==1?1:0;
			$update = $model->updateAdminGroup(array('group_id'=>$gid), $data);
			// --- ---
			if ($update){
				$this->log(L('nc_edit,limit_gadmin').'['.$_POST['group_name'].']',1);
				showMessage(L('nc_common_save_succ'),'index.php?act=admin&op=group');
			}else {
				showMessage(L('nc_common_save_succ'));
			}
		}
		//解析已有权限
		$hlimit = decrypt($ginfo['group_limits'],MD5_KEY.md5($ginfo['group_name']));
		$ginfo['limits'] = explode('|',$hlimit);
		Tpl::output('ginfo',$ginfo);
        Tpl::output('limit',$this->permission());
		Tpl::output('top_link',$this->sublink($this->links, 'group'));
		Tpl::showpage('admin.group.edit1');
	}

	// 删除
	public function group_delOp(){
		if (is_numeric($_GET['group_id'])){
			$model = Model('admin_group');
			$ginfo = $model->getby_group_id($_GET['group_id']);
			$admin_info = $this->getAdminInfo();
			if($ginfo['is_super_group']==1 && $admin_info['id']!=1){
				//属于超级权限组 其他管理员无权编辑
				showMessage('该权限组属于超级管理权限组,您无权删除');
			}
			Model('admin_group')->where(array('group_id'=>intval($_GET['group_id'])))->delete();
			$this->log(L('nc_delete,limit_gadmin').'[ID'.intval($_GET['group_id']).']',1);
			redirect();
		}else {
			showMessage(L('nc_common_op_fail'));
		}
	}


}